package gspushmq.v1.save.log;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.java_websocket.WebSocket;

import ggframework.mongodb.BasicDBObject;
import ggframework.mongodb.DBCollection;
import ggframework.mongodb.DBObject;
import gspushmq.model.Message;
import gspushmq.model.User;
import gspushmq.util.GGLogger;
import gspushmq.util.MongoUtil;
import gspushmq.v1.produce.job.core.GGServiceJob;
import gspushmq.v1.subscribe.GGSubscribe;

/**
 *
 * 写入订阅记录
 * @version 1.0
 * @since JDK1.7
 * @author yutao
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
 * @date 2018年11月8日上午10:24:58
 */
public class LogWriteJob  extends GGServiceJob {

	static List<DBObject> messLogPool = new ArrayList<DBObject>();
	@Override
	public void doServiceJob(Map<String, Object> args) {
		LogQueue q = LogQueue.queue;
		while (true) {
			LogBean log = q.get();
			
			if (log != null) {
				writeSubscribeLog(log);
				if (messLogPool.size() >= 1000) {
					save();
				}
			} else {
				if (messLogPool.isEmpty()) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}else {
					save();
				}
			}
		}
		
	}

	
	
	/**
	 * 写订阅日志
	 * @author yutao
	 * @date 2018年11月21日下午4:26:54
	 */
	private void writeSubscribeLog(LogBean log) {

		GGLogger.info(getClass(), "-=-=-=-开始写订阅日志-=-=-");

		try {
			BasicDBObject fieldMap = new BasicDBObject();
			fieldMap.put("status", log.getStatus());
			Message mess = log.getMessage();
			BeanInfo beanInfo;
			beanInfo = Introspector.getBeanInfo(mess.getClass(), Object.class);

			// 获取所有的属性描述器
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor pd : pds) {
				String key = pd.getName();
				if ("wst".equals(key)) {
					if (mess.getWst() != null) {
						WebSocket wst = mess.getWst();
						User user = GGSubscribe.wstUser.get(wst);
						fieldMap.put("user", user == null ? null : user.toString());
						fieldMap.put(key, mess.getWst().toString());
					}
					continue;
				}
				Method getter = pd.getReadMethod();
				Object obj = getter.invoke(mess);

				fieldMap.put(key, obj);
			}

			if (mess instanceof Message) {
				fieldMap.append("insert_time", new Date());
				messLogPool.add(fieldMap);
			}
		} catch (Exception e) {
			GGLogger.error(getClass(), "---bean转map---出错---" + e.toString());
			e.printStackTrace();
		}

	}
	
	private void save() {
		if (!messLogPool.isEmpty()) {//订阅日志
			DBCollection messRecord = MongoUtil.getFtAccountBehaviorCollection("cabs_msg_subscribe_record");
			messRecord.insert(messLogPool);
			messLogPool.clear();
		}
	}

}
